package com.onemore.plugin.omp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;

import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.util.string.MD5;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.RequestCallback;
import com.onemore.sfpt.ConstantData;
import com.netease.nim.uikit.DemoCache;
import com.onemore.sfpt.module.im.activity.SessionListActivity;
import com.onemore.sfpt.module.im.preference.Preferences;
import com.onemore.sfpt.module.login.view.LoginActivity;
import com.onemore.sfpt.utils.SharedPreferencesUtil;

import com.netease.nimlib.sdk.auth.LoginInfo;
import com.onemore.sfpt.utils.Util;

/**
 * This class echoes a string called from JavaScript.
 */
public class omp extends CordovaPlugin {

    private String TAG = "omp";

    private CallbackContext context;

    private Activity activity;

    private AbortableFuture<LoginInfo> loginRequest;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        this.context = callbackContext;
        this.activity = this.cordova.getActivity();

        if (action.equals("getUserInfo")) {
//            String message = args.getString(0);
            this.getUserInfo("", callbackContext);
            return true;
        }

        if (action.equals("logout")) {
//            String message = args.getString(0);
            this.logout("", callbackContext);
            return true;
        }

        if (action.equals("callNativeModule")) {
            Log.e(TAG, "execute-callNativeModule");
            if(args.length() > 0 ) {
                String cmd = args.getString(0);
                //String message = args.getString(0);
                this.callNativeModule(cmd, callbackContext);
            }
            return true;
        }
        return false;
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }

    private void getUserInfo(String message, CallbackContext callbackContext) {
        Log.e("omp","getUserInfo");
        String userInfo = SharedPreferencesUtil.getString(this.cordova.getContext(), ConstantData.SHAREDPREFERENCES_NAME,ConstantData.USER_INFO,"");

        if(userInfo.isEmpty()){
            callbackContext.error("Expected one non-empty string argument.");
        } else {
            callbackContext.success(userInfo);
        }
    }

    private void logout(String message, CallbackContext callbackContext) {
        Context context=this.cordova.getActivity().getApplicationContext();

        SharedPreferencesUtil.setString(this.cordova.getContext(), ConstantData.SHAREDPREFERENCES_NAME,ConstantData.USER_INFO,"");

        Util.cleanUserLoginInfo(context);
        Util.cleanIMTokenInfo(context);

        Intent intent=new Intent(context,LoginActivity.class);
        intent.putExtra("logout","logout");
        context.startActivity(intent);
        this.cordova.getActivity().finish();
    }

    private void callNativeModule(String name, CallbackContext callbackContext) {
        switch (name.toLowerCase()){
            case "im":
                //跳转到IM界面
                Intent intent = new Intent(activity, SessionListActivity.class);
                //        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivityForResult(intent,100);
                break;
            case "ocr":
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if(resultCode==Activity.RESULT_OK){
            String spot=intent.getStringExtra("spot");
            context.success(spot);
        }
    }

    //DEMO中使用 username 作为 NIM 的account ，md5(password) 作为 token
    //开发者需要根据自己的实际情况配置自身用户系统和 NIM 用户系统的关系
    private String tokenFromPassword(String password) {
        String appKey = readAppKey(this.cordova.getContext());
        boolean isDemo = "45c6af3c98409b18a84451215d0bdd6e".equals(appKey)
                || "fe416640c8e8a72734219e1847ad2547".equals(appKey);

        return isDemo ? MD5.getStringMD5(password) : password;
    }

    private String readAppKey(Context context) {
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (appInfo != null) {
                return appInfo.metaData.getString("com.netease.nim.appKey");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }
}
